package com.imdroid.web.listener;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServlet;

import com.imdroid.udp.UDPServer;

@WebListener
public class UDPConnectionListener extends HttpServlet implements
		ServletContextListener {
	/**
	 * The serial version uuod
	 */
	private static final long serialVersionUID = 2747819614284163822L;

	/**
	 * The thread of worker
	 */
	// private Thread thread;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
	 * ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		UDPServer.shutdown();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.ServletContextListener#contextInitialized(javax.servlet
	 * .ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent sce) {
		try {
			UDPServer.startup(3001);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * The runner of the upd connection
	 * 
	 */
	class UDPConnectionRunner implements Runnable {
		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		public void run() {
			try {
				DatagramSocket socket = new DatagramSocket(3001);
				DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
				while (true) {
					socket.receive(packet);
				}
			} catch (Exception e) {

				e.printStackTrace();
			}

		}
	}
}
